//
//  MCTimeRangeViewController.swift
//  StoreManage
//
//  Created by MC on 2018/8/10.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

typealias MCTimeRangeViewControllerClosure = (_ start:String,_ end:String) -> Void

class MCTimeRangeViewController: MCViewController {

    
    var closure : MCTimeRangeViewControllerClosure?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        managerClosure()
        
        sendNetworking()
        
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Closure
    func managerClosure() {
        datePicker.datePickerClosure = { timeStr in
            self.dateChanged(timeStr: timeStr)
        }
    }
    
    // MARK: - Action
    @objc func rightItemClicked() {
        
        var start = ""
        var end = ""

        
        // 按日查询
        if chooseButton.isSelected {
            
            if deleteButton.isSelected {
                start = ""
                end = ""
            } else {
                if leftButton.nameLabel.text == "开始时间" || rightButton.nameLabel.text == "结束时间" {
                    MCHUD_text(message: "请选择时间", view: self.view, delay: 1.2)
                    return
                }
                
                start = leftButton.nameLabel.text ?? ""
                end = rightButton.nameLabel.text ?? ""
                
                let formatter = DateFormatter()
                //日期样式
                formatter.dateFormat = "yyyy-MM-dd"
                let locale = Locale.init(identifier: "zh_CN")
                formatter.locale = locale
                let startDate = formatter.date(from: start)
                start = formatter.string(from: startDate!)
                
                
                let endDate = formatter.date(from: end)
                end = formatter.string(from: endDate!)

            }
            
            closure?(start,end)
        } else {  // 按月查询
            
            if deleteButton.isSelected {
                start = ""
                closure?("","")
            } else {
                if leftButton.nameLabel.text == "选择月份" {
                    MCHUD_text(message: "请选择时间", view: self.view, delay: 1.2)
                    return
                }
                
                let time = leftButton.nameLabel.text ?? ""
                start = time + "-01 00:00:00"
                
                let formatter = DateFormatter()
                //日期样式
                formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                let locale = Locale.init(identifier: "zh_CN")
                formatter.locale = locale
                let startDate = formatter.date(from: start)
                start = formatter.string(from: startDate!)
                
                let endDate = endOfCurrentMonth(date: startDate!, returnEndTime: true)
                end = formatter.string(from: endDate)
                
                closure?(start,end)
            }
            
            
            
            

        }
        
        navigationController?.popViewController(animated: true)
    }
    
    //本月结束日期
    func endOfCurrentMonth(date:Date,returnEndTime:Bool = false) -> Date {
        let calendar = NSCalendar.current
        var components = DateComponents()
        components.month = 1
        if returnEndTime {
            components.second = -1
        } else {
            components.day = -1
        }
        
        let endOfMonth =  calendar.date(byAdding: components, to: date)!
        return endOfMonth
    }
    
    @objc func deleteButtonClicked() {
        chooseButton.isSelected = true
        chooseButtonClicked()
        leftButton.isSelected = false
        datePicker.isHidden = true
        leftButton.nameLabel.text = "选择月份"
        datePicker.settingPickerView(mode: MCDateMode.year_month)
        
        deleteButton.isSelected = true
    }
    
    @objc func chooseButtonClicked() {
        
        
        chooseButton.isSelected = !chooseButton.isSelected

        datePicker.isHidden = false

        if chooseButton.isSelected {
            
            datePicker.settingPickerView(mode: MCDateMode.year_month_day)

            
            leftButton.isSelected = true
            rightButton.isSelected = false
            
            rightButton.isHidden = false
            promptLabel.isHidden = false
            
            leftButton.nameLabel.text = "开始时间"
            rightButton.nameLabel.text = "结束时间"

            
            leftButton.snp.remakeConstraints { (make) ->Void in
                make.left.equalTo(15)
                make.right.equalTo(promptLabel.snp.left)
                make.centerY.equalTo(promptLabel)
                make.height.equalTo(40)
            }
            
            rightButton.snp.remakeConstraints { (make) ->Void in
                make.right.equalTo(-15)
                make.left.equalTo(promptLabel.snp.right)
                make.centerY.equalTo(promptLabel)
                make.height.equalTo(40)
            }
        } else {
            leftButton.isSelected = true
            rightButton.isHidden = true
            promptLabel.isHidden = true
            leftButton.nameLabel.text = "选择月份"
            
            datePicker.settingPickerView(mode: MCDateMode.year_month)

            
            leftButton.snp.remakeConstraints { (make) ->Void in
                make.left.equalTo(15)
                make.right.equalTo(-15)
                make.centerY.equalTo(promptLabel)
                make.height.equalTo(40)
            }
        }
        
        datePicker.callBack()
        deleteButton.isSelected = false
    }
    
    @objc func leftButtonClicked() {
        

        datePicker.isHidden = false
        leftButton.isSelected = true
        rightButton.isSelected = false
        datePicker.callBack()
        deleteButton.isSelected = false
    }
    
    @objc func rightButtonClicked() {

        datePicker.isHidden = false
        leftButton.isSelected = false
        rightButton.isSelected = true
        datePicker.callBack()
        deleteButton.isSelected = false
    }

    @objc func dateChanged(timeStr:String) {

        if leftButton.isSelected {
            leftButton.nameLabel.text = timeStr
        } else {
            rightButton.nameLabel.text = timeStr
        }
    }
    
    // MARK: - Network
    func sendNetworking() {
        
    }
    
    // MARK: - Method
    func baseSetting() {
        self.title = "选择时间"
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("确定", target: self, selector: #selector(rightItemClicked))        
    }
    
    func initUI() {
        view.addSubview(chooseButton)
        chooseButton.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(15)
            make.top.equalTo(20)
            make.size.equalTo(CGSize.init(width: 90, height: 30))
        }
        
        view.addSubview(deleteButton)
        deleteButton.snp.remakeConstraints { (make) ->Void in
            make.right.equalTo(-15)
            make.centerY.equalTo(chooseButton)
            make.size.equalTo(CGSize.init(width: 30, height: 30))
        }
        
        
        view.addSubview(promptLabel)
        promptLabel.snp.remakeConstraints { (make) ->Void in
            make.centerX.equalTo(view)
            make.width.equalTo(30)
            make.top.equalTo(chooseButton.snp.bottom).offset(80)
        }
        
        view.addSubview(leftButton)
        leftButton.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerY.equalTo(promptLabel)
            make.height.equalTo(40)
        }
        
        view.addSubview(rightButton)
        rightButton.snp.remakeConstraints { (make) ->Void in
            make.right.equalTo(-15)
            make.left.equalTo(promptLabel.snp.right)
            make.centerY.equalTo(promptLabel)
            make.height.equalTo(40)
        }

        
        
        let width = (MCScreenWidth - 30)
        
        view.addSubview(datePicker)
        datePicker.snp.remakeConstraints { (make) ->Void in
            make.top.equalTo(promptLabel.snp.bottom).offset(60)
            make.size.equalTo(CGSize.init(width: width, height: 216))
            make.left.equalTo(15)
        }
    }
    
    // MARK: - Setter & Getter
    lazy var chooseButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.backgroundColor = UIColor.init(white: 0, alpha: 0.05)
        button.layer.cornerRadius = 3
        button.layer.masksToBounds = true
        button.layer.borderColor = UIColor.MCGray_middle.cgColor
        button.layer.borderWidth = 1
        button.titleLabel?.font = MCFont(14)
        button.setTitle("按月查询", for: .normal)
        button.setTitle("按日查询", for: .selected)
        

        button.setTitleColor(UIColor.MCWords, for: .normal)
        
        button.setImage(#imageLiteral(resourceName: "Bill_change"), for: .normal)

        button.imageEdgeInsets = UIEdgeInsetsMake(0, 70, 0, 0)
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 20)
        
        button.addTarget(self, action: #selector(chooseButtonClicked), for: .touchUpInside)
        return button
    }()
    
    lazy var deleteButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.setImage(#imageLiteral(resourceName: "Reuse_delete").MCImageWithTintColor(color: UIColor.MCGray_middle), for: .normal)
        button.setImage(#imageLiteral(resourceName: "Reuse_delete").MCImageWithTintColor(color: UIColor.MCGray_middle), for: .selected)

        button.addTarget(self, action: #selector(deleteButtonClicked), for: .touchUpInside)

        return button
    }()
    
    
    lazy var leftButton: MCTimeRangeChooseButton = {
        let button = MCTimeRangeChooseButton()
        button.nameLabel.text = "开始时间"
        button.isSelected = true
        button.addTarget(self, action: #selector(leftButtonClicked), for: .touchUpInside)
        return button
    }()
    
    lazy var promptLabel: UILabel = {
        let label = UILabel()
        label.font = MCFont(14)
        label.text = "至"
        label.isHidden = true
        label.textColor = UIColor.MCGray_middle
        label.textAlignment = NSTextAlignment.center
        return label
    }()
    
    lazy var rightButton: MCTimeRangeChooseButton = {
        let button = MCTimeRangeChooseButton()
        button.nameLabel.text = "结束时间"
        button.isHidden = true

        button.addTarget(self, action: #selector(rightButtonClicked), for: .touchUpInside)
        return button
    }()
    
    
    lazy var datePicker: MCDatePicker = {
        let p = MCDatePicker()
        p.titleFont = 14
        p.maximumDate = Date.init()
        p.settingPickerView(mode: MCDateMode.year_month)
        return p
    }()
}


class MCTimeRangeChooseButton: UIButton {
   
    override var isSelected: Bool {
        didSet {
            if isSelected {
                nameLabel.textColor = UIColor.MCMain
                lineView.backgroundColor = UIColor.MCMain
                
            } else {
                nameLabel.textColor = UIColor.MCGray_middle
                lineView.backgroundColor = UIColor.MCGray_middle
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(lineView)
        lineView.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(1.5)
        }
        
        self.addSubview(nameLabel)
        nameLabel.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(self).inset(UIEdgeInsetsMake(0, 5, 1.5, 5))
        }
        
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = MCFont(15)
        label.textColor = UIColor.MCGray_middle
        label.textAlignment = NSTextAlignment.center
        return label
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.MCGray_middle
        
        return view
    }()
}
